<!--
 * @Author       : 震雨 LuckRain7
 * @Date         : 2020-07-22
 * @Description  : 登录组件
 * @ Love and Peace

 登录逻辑：
    1、用户输入账号、密码、验证码
    2、用户点击 登录按钮，对用户名和密码、验证码进行校核
    3、向服务器发送请求（无token限制的请求）
    4、接收服务器返回的数据
        - 将服务器返回的 token 进行存储
        - 向服务器发送请求，请求 路由权限（如果是服务器返回路由的话）、用户信息、权限信息等
    5、进行路由跳转，跳转到 home 页面
    6、加密：js-md5 base64

-->

<template>
  <common-layout>
    <div class="top">
      <div class="header">
        <img alt="logo" class="logo" src="@/assets/img/logo.png" />
        <span class="title">{{ systemName }}</span>
      </div>
      <div class="desc">世界的七河 七河的世界</div>
      <a href="http://111.17.201.197:55000/purchase/#/home" target="_blank">0009090909</a>
    </div>
    <div class="login">
      <a-form-model ref="ruleForm" :model="Form" :rules="rules">
        <a-tabs
          size="large"
          :tabBarStyle="{ textAlign: 'center' }"
          style="padding: 0 2px"
        >
          <a-tab-pane tab="工号密码登录" key="1">
            <a-alert
              type="error"
              :closable="true"
              v-show="error"
              :message="error"
              showIcon
              style="margin-bottom: 24px"
            />
            <!--  -->
            <a-form-model-item prop="workNo" ref="workNo">
              <a-input
                size="large"
                placeholder="请输入账户名"
                v-model="Form.workNo"
              >
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-model-item>
            <!--  -->
            <a-form-model-item prop="password" ref="password">
              <a-input-password
                size="large"
                placeholder="请输入密码"
                type="password"
                v-model="Form.password"
              >
                <a-icon slot="prefix" type="lock" />
              </a-input-password>
            </a-form-model-item>
            <!--  -->

            <a-row :gutter="20">
              <a-col :span="16">
                <a-form-model-item prop="captcha" ref="captcha">
                  <a-input
                    size="large"
                    placeholder="请输入验证码"
                    v-model="Form.captcha"
                    @focus="getCaptcha"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" class="login-captcha">
                <img
                  :src="randCodeImage"
                  @click="getCaptcha()"
                  alt
                  class="yanzhengma"
                />
              </a-col>
            </a-row>
          </a-tab-pane>
          <!--  -->

          <!-- 手机号登录方式 -->
          <!-- <a-tab-pane tab="手机号登录" key="2">
            <a-form-item>
              <a-input size="large" placeholder="mobile number">
                <a-icon slot="prefix" type="mobile" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-row :gutter="8" style="margin: 0 -4px">
                <a-col :span="16">
                  <a-input size="large" placeholder="captcha">
                    <a-icon slot="prefix" type="mail" />
                  </a-input>
                </a-col>
                <a-col :span="8" style="padding-left: 4px">
                  <a-button
                    style="width: 100%"
                    class="captcha-button"
                    size="large"
                    >获取验证码</a-button
                  >
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane>-->
        </a-tabs>
        <div style="margin-top: 10px">
          <a-checkbox v-model="isRemember">记住密码</a-checkbox>
          <a style="float: right">忘记密码</a>
        </div>
        <a-form-item>
          <a-button
            :loading="logging"
            style="width: 100%; margin-top: 24px"
            size="large"
            htmlType="submit"
            type="primary"
            @click="onSubmit"
            >登录</a-button
          >
        </a-form-item>
        <!-- <div>
          其他登录方式
          <a-icon class="icon" type="alipay-circle" />
          <a-icon class="icon" type="taobao-circle" />
          <a-icon class="icon" type="weibo-circle" />
          <router-link style="float: right" to="/dashboard/workplace" >注册账户</router-link>
        </div>-->
        <div>
          祝您开心快乐工作每一天
          <a-icon
            type="heart"
            theme="twoTone"
            two-tone-color="#eb2f96"
            style="margin-right: 6px; font-size: 16px"
          />
          <a-icon
            type="heart"
            theme="twoTone"
            two-tone-color="#eb2f96"
            style="margin-right: 6px; font-size: 16px"
          />
          <a-icon
            type="heart"
            theme="twoTone"
            two-tone-color="#eb2f96"
            style="margin-right: 6px; font-size: 16px"
          />
        </div>
      </a-form-model>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from "@/layouts/CommonLayout";
import { LoginHttpUl } from "@/services/modules/login.js";

const $loginHttpUl = new LoginHttpUl();
// const $LoginHttpL = new LoginHttpL();

import CryptoJS from "crypto-js/crypto-js"; // BASE64

export default {
  name: "Login",
  components: { CommonLayout },
  data() {
    return {
      logging: false, // 登录状态
      error: "",
      currdatetime: "",
      randCodeImage: "", // 验证码 base64
      requestCodeSuccess: null, //
      test: {},
      isRemember: true,

      // 表单
      Form: {
        workNo: "",
        password: "",
        captcha: "",
      },
      // 规则
      rules: {
        workNo: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        captcha: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
      },
    };
  },

  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },
  },

  mounted() {
    this.getCaptcha();
    this.$nextTick(() => {
      // --- 浏览器判断 ---
      const h = this.$createElement;
      if (this.browserIsIE()) {
        // const h = this.$createElement;
        this.$error({
          title: "这里是浏览器兼容性提醒！",
          content: h("div", {}, [
            h("p", "系统检测到您使用的浏览器是IE内核"),
            h("p", "相关建议："),
            h("p", "- 请更换谷歌浏览器、火狐浏览器 或 QQ浏览器"),
            h("p", "- 360浏览器请切换到极速模式"),
          ]),
        });
      }

      // // --- 设置记住密码 ---
      // const stateLogin = this.$store.state.user.login;
      // if (stateLogin) {
      //   this.form.setFieldsValue({
      //     password: stateLogin.password, // 密码
      //     workNo: stateLogin.workNo, // 工号
      //   });
      // }
      // --- ---
    });
    this.getBase64();
  },

  methods: {
    getBase64(rawStr) {
      let wordArray = CryptoJS.enc.Utf8.parse(rawStr);
      let base64 = CryptoJS.enc.Base64.stringify(wordArray);
      return base64;
    },
    // 点击登录按钮
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.logging = true;
          // 拼接 post 数据
          const options = {
            captcha: this.Form.captcha, // 验证码
            checkKey: this.currdatetime, // 验证码key
            password: this.getBase64(this.Form.password), // 密码
            // password: this.Form.password,
            workNo: this.Form.workNo, // 工号
          };
          console.log(options);
          // 发送请求
          $loginHttpUl.login(options).then((res) => {
            // 进行 账号密码或验证码 验证
            if (res.code == 500) {
              // 用户名或者密码错误
              this.$message.error(res.message, 3);
              this.logging = false;
              this.getCaptcha();
            } else {
              // 存储 token
              localStorage.setItem(
                "zhqh-pro-token",
                JSON.stringify(res.result.token)
              );
              // Vuex 保存用户信息 | 部门信息
              this.$store.commit("user/setUserInfo", res.result.userInfo);
              this.$store.commit("user/setDepartments", res.result.departs);
              this.$store.dispatch("user/getPositionById"); // 拿到职务信息
              // 这里拿到路由后进行的跳转,但是页面中的菜单还是没有显示
              this.$store.dispatch("user/getButtonRights"); // 拿到按钮权限
              this.$store.dispatch("user/getMenuRights"); // 拿到路由权限

              this.$message.success("登录成功", 3); // 信息提示
              this.checkdefaultPassword(); //检查密码是否是888888
              setTimeout(() => {
                this.$router.push("/home");
              }, 1000);
            }
            // // 路由跳转
          });
        } else {
          return false;
        }
      });
    },
      //密码为888888跳转到修改密码页面
    checkdefaultPassword() {
      if (this.Form.password === "888888") {
        setTimeout(() => {
          this.$router.push("/personalCenter");
        }, 3000);
      } else {
        setTimeout(() => {
          this.$router.push("/home");
        }, 1000);
      }
    },
    // 获取验证码
    getCaptcha() {
      // 获取当前时间
      this.currdatetime = new Date().getTime();

      // ajax 请求
      $loginHttpUl
        .getCaptcha(this.currdatetime)
        .then((res) => {
          this.randCodeImage = res.result;
          this.requestCodeSuccess = true;
        })
        .catch(() => {
          this.requestCodeSuccess = false;
        });
    },

    // --- 浏览器判断函数 ---
    browserIsIE() {
      const inBrowser = typeof window !== "undefined",
        UA = inBrowser && window.navigator.userAgent.toLowerCase(),
        isIE = UA && /msie|trident/.test(UA);
      return isIE;
    },
  },
};
</script>

<style lang="less" scoped>
.common-layout {
  .top {
    text-align: center;
    .header {
      height: 44px;
      line-height: 44px;
      a {
        text-decoration: none;
      }
      .logo {
        height: 44px;
        vertical-align: top;
        margin-right: 16px;
      }
      .title {
        font-size: 33px;
        color: @title-color;
        font-family: "Myriad Pro", "Helvetica Neue", Arial, Helvetica,
          sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
      }
    }
    .desc {
      font-size: 14px;
      color: @text-color-second;
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }
  .login {
    width: 368px;
    margin: 0 auto;
    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }
    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
  }
}
</style>
